package com.andy.basics;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;

public abstract class Converter<T extends Entity> implements javax.faces.convert.Converter {

	protected static Logger rootLogger = Logger.getLogger(Converter.class);

	public abstract Dao<T> getDao();

	public Object getAsObject(final FacesContext context, final UIComponent component, final String value) {

		Object obj = this.asObject(value);
		if (obj != null) {
			return obj;
		}
		for (T mt : this.getDao().findAll()) {
			if (mt instanceof NamedEntity) {
				NamedEntity e = (NamedEntity) mt;
				if ((e.getName() != null) && e.getName().equals(value)) {
					return mt;
				}
			}
			if (mt instanceof Entity) {
				Entity e = mt;
				if (e.getId().equals(value)) {
					return mt;
				}
			}

		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public String getAsString(final FacesContext context, final UIComponent component, final Object value) {

		if (value == null) {
			return "None";
		}

		String str = this.asString((T) value);

		if (str != null) {
			return str;
		}

		if (value instanceof NamedEntity) {
			String val = ((NamedEntity) value).getName();
			return (val == null) || (val.length() == 0) ? "None" : val;
		}
		if (value instanceof Entity) {
			String val = ((Entity) value).getId().toString();
			return (val == null) || (val.length() == 0) ? "None" : val;
		}
		return "None";
	}

	public String asString(final T value) {
		return null;
	}

	public T asObject(final String value) {
		return null;
	}
}
